from flask import Flask
from multiprocessing import Pool
from flask import request
import itchat, time
from onlineUntil.mysqlConnection import insert,update,select
app = Flask(__name__)
import uuid
@app.route('/')
def getHtml():
    return app.send_static_file("login.html")
#获取登陆ID
@app.route('/getImg')
def hello_world():
    loginid = str(uuid.uuid1());
    p = Pool()
    p.apply_async(func=login,args=(loginid,))
    time.sleep(3)
    img = "static/" + loginid + ".jpg"
    result = img + "&" + loginid
    return result


# 提交发送内容
@app.route('/submitKey',methods=['GET', 'POST'])
def submitKey():
    loginID = request.form.get('loginID')
    key = request.form.get('key')
    print(loginID+key)
    loginState = select("select login_state from wechat.login where login_id = '{}'".format(loginID))
    if loginState['login_state'] == 1:
        print("login success")
        update("update wechat.login set send_content = '{}+(关注微信公众号：IT这行,免费使用微信群发)' where login_id = '{}'".format(key,loginID))
        return "success"
    return "fail"

# 登陆方法
def login(loginid):
    imgName = "static/" + loginid + ".jpg"
    # 登陆二维码名称入库
    insert("INSERT into wechat.login(qr_name,login_id,login_time) VALUES('{}','{}',now())".format(imgName,loginid))
    #imgName = "static/123.jpg"
    itchat.auto_login(picDir=imgName)
    print("login success")
    #itchat.run()
    # 更新登陆状态
    update("UPDATE wechat.login SET login_state = 1 WHERE login_id = '{}'".format(loginid))
    flag = True
    while(flag):
        resultData = select("SELECT send_content FROM wechat.login WHERE login_id = '{}'".format(loginid))
        if resultData == None:
            flag = True
            continue
        else:
            flag = False
            friendList = itchat.get_friends(update=True)[1:]
            for friend in friendList:
                #print(friend.RemarkName+"+"+friend.UserName)
                itchat.send_msg(msg=resultData,toUserName=friend.UserName)
            itchat.logout()

if __name__ == '__main__':

    app.run(host="0.0.0.0",port="8090",threaded=True)